#Usage:  Rscript survival_plot.R -jt test_survival.csv -c LIHC -s os/PFS -m mean/median


library(getopt)
library(survival)
library(survminer)
spec <- matrix(
  c("junction_table",  "jt", 2, "character", "This is cpm table!",
    "cancer","c",2,"character","which cancer",
    "status", "s",2, "character",  "PFI or os",
    "mean_median","m",2,"character","median or mean"),
  byrow=TRUE, ncol=5)
args=getopt(spec)
data=read.csv(args$junction_table,header=F)
cancer=args$cancer
s1="OS"
if (args$s=="PFI"){s1="PFI"}
type=args$type
time=paste(s1,"_time",sep="")
colnames(data)=c("Sample_barcode","Cancer_type","Sample_type","OS","OS_time","PFI","PFI_time","junction")
data=data[which(data$Cancer_type==cancer),]
data=na.omit(data)
if (args$m=="mean"){
  data$status=ifelse(data$junction>mean(data$junction), "high", "low")
}else{
  data$status=ifelse(data$junction>median(data$junction), "high", "low")
}

sur<- survfit(Surv(data[,time],data[,s1]) ~data[,'status'], data =data)
pdf(file="surv_plot.pdf",width=6.5,height=6,onefile = FALSE)
p = ggsurvplot(sur,data=data,
           risk.table = TRUE,
           surv.median.line = "hv",
           legend.labs = c("high", "low"),
           pval = TRUE) + labs(x = "Time (days)")
print(p)
dev.off()

